#include "kernel_operator.h"
#include "math.h"

constexpr int32_t TOTAL_LENGTH = 2048;
constexpr int32_t USE_CORE_NUM = 8;
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;
constexpr int32_t TILE_NUM = 8;
constexpr int32_t BUFFER_NUM = 2;
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM;

using namespace AscendC;




template<typename TYPE_X, typename TYPE_Z,bool IsExistBigCore> 
class KernelSinc {
public:
    __aicore__ inline KernelSinc() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, uint64_t smallCoreDataNum,
                                uint64_t bigCoreDataNum, uint64_t bigCoreLoopNum, 
                                uint64_t smallCoreLoopNum, uint64_t ubPartDataNum, 
                                uint64_t smallCoreTailDataNum, uint64_t bigCoreTailDataNum, 
                                uint64_t tailBlockNum) 
    {
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint64_t coreNum = AscendC::GetBlockIdx();
        uint64_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->ubPartDataNum = ubPartDataNum;
        if constexpr (IsExistBigCore) 
        {
          if (coreNum < tailBlockNum) 
          { 
            this->coreDataNum = bigCoreDataNum;
            this->tileNum = bigCoreLoopNum;
            this->tailDataNum = bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = smallCoreDataNum;
            this->tileNum = smallCoreLoopNum;
            this->tailDataNum = smallCoreTailDataNum;
            globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = smallCoreLoopNum;
          this->tailDataNum = smallCoreTailDataNum;
          globalBufferIndex = smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ TYPE_Z*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Z));

    
        pipe.InitBuffer(tmpbuf1 , this->ubPartDataNum * sizeof(TYPE_Z));
        pipe.InitBuffer(tmpbuf2 , this->ubPartDataNum);

        pipe.InitBuffer(tmpbuf4 , this->ubPartDataNum * sizeof(TYPE_Z));
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;
        for (int32_t i = 0; i < loopCount-1; i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;
        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
      AscendC::DataCopy(xLocal, xGm[progress * this->ubPartDataNum], this->processDataNum);
      inQueueX.EnQue(xLocal);
    }

    __aicore__ inline void Compute(int32_t progress)//sin(pi x)/(pi*x)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.AllocTensor<TYPE_Z>();
    
        int sz=this->processDataNum;

        AscendC::LocalTensor<TYPE_Z> tmp= tmpbuf1.Get<TYPE_Z>();
        AscendC::LocalTensor<uint8_t> tmp2= tmpbuf2.Get<uint8_t>();
        AscendC::LocalTensor<TYPE_Z> tmp4= tmpbuf4.Get<TYPE_Z>();

        AscendC::Abs(xLocal, xLocal, sz); //abs(x)

        AscendC::DataCopy(tmp4, xLocal, sz); 


        const unsigned u=0x7f000000;
	      float mx= (*(float *)(&u));

        for(float s=(mx);s>=2.0f;s/=2.0f){
            AscendC::CompareScalar(tmp2, xLocal, (TYPE_Z)s, AscendC::CMPMODE::GE, sz);
            AscendC::Adds(tmp, xLocal, (TYPE_Z)-s, sz); //x - s
            AscendC::Select(xLocal, tmp2, tmp, xLocal, AscendC::SELMODE::VSEL_TENSOR_TENSOR_MODE, sz);
        }//AscendC::Fmod(xLocal, xLocal, (TYPE_X)2, sz); //x fmod 2


        AscendC::CompareScalar(tmp2, xLocal, (TYPE_Z)2.0f, AscendC::CMPMODE::GE, sz);
        AscendC::Adds(tmp, xLocal, (TYPE_Z)-2.0f, sz); //x - s
        AscendC::Select(xLocal, tmp2, tmp, xLocal, AscendC::SELMODE::VSEL_TENSOR_TENSOR_MODE, sz);

        AscendC::CompareScalar(tmp2, xLocal, (TYPE_Z)1.0f, AscendC::CMPMODE::GE, sz);
        AscendC::Adds(tmp, xLocal, (TYPE_Z)-2.0f, sz); //x - s
        AscendC::Select(xLocal, tmp2, tmp, xLocal, AscendC::SELMODE::VSEL_TENSOR_TENSOR_MODE, sz);


        AscendC::Muls(xLocal, xLocal, (TYPE_Z)3.14159265358979323846, sz); //pi*x
     
        //sin(pi*x) = pi*x - (pi*x)^3/6 + (pi*x)^5/120 - (pi*x)^7/5040 + (pi*x)^9/362880 - ...
        //AscendC::Duplicate(zLocal, (TYPE_X)1.0f ,sz);
        //AscendC::Duplicate(tmp, (TYPE_X)1.0f ,sz);
        AscendC::DataCopy(zLocal, xLocal, sz); //zLocal = pi*x
        AscendC::DataCopy(tmp, xLocal, sz); //tmp = pi*x

        for(int i=1; i<19; i++){
            AscendC::Mul(tmp, tmp, xLocal, sz); //
            AscendC::Mul(tmp, tmp, xLocal, sz); //tmp = tmp* xLocal^2
            AscendC::Muls(tmp, tmp, (TYPE_Z)(-1.0f/(2.0f*i)), sz); //tmp = (pi*x)^3/6
            AscendC::Muls(tmp, tmp, (TYPE_Z)(1.0f/(1.0f+ 2.0f*i)), sz); //tmp = (pi*x)^3/6
            AscendC::Add(zLocal, zLocal, tmp, sz); //zLocal = zLocal - (pi*x)^3/6
        }//AscendC::Sin(zLocal, tmp, sz); //sin(pi*x)
        
        //continue the series expansion if needed
        AscendC::CompareScalar(tmp2, tmp4, (TYPE_Z)1e-4f, AscendC::CMPMODE::GT, sz);
        AscendC::Select(tmp4, tmp2, tmp4, (TYPE_Z)1e-4f, AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, sz);
        AscendC::Div(zLocal, zLocal, tmp4, sz); //sin(pi*x)/(pi*x)
        AscendC::Muls(zLocal, zLocal, (TYPE_Z)(1.0/3.14159265358979323846), sz); 

      outQueueZ.EnQue<TYPE_Z>(zLocal);
      inQueueX.FreeTensor(xLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.DeQue<TYPE_Z>();  
      AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
      outQueueZ.FreeTensor(zLocal);
    }
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpbuf1,tmpbuf2,tmpbuf4;
    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Z> zGm;
    uint64_t coreDataNum;
    uint64_t tileNum;
    uint64_t ubPartDataNum;
    uint64_t tailDataNum;
    uint64_t processDataNum;
};

//GM_ADDR input, GM_ADDR out, uint32_t size, uint32_t length,TPipe *PIPE)
  
extern "C" __global__ __aicore__ void sinc_custom(GM_ADDR input, GM_ADDR out)
{
    // GET_TILING_DATA(tiling_data, tiling);
    KernelSinc<float, float, 0 >op;
    op.Init(input, out, 
            TOTAL_LENGTH, TOTAL_LENGTH, 
            TOTAL_LENGTH/64, TOTAL_LENGTH/64, 
            64,
            64,64,33);


    /*
     op.Init(x, z, 
                tiling_data.smallCoreDataNum, tiling_data.bigCoreDataNum, 
                tiling_data.bigCoreLoopNum,   tiling_data.smallCoreLoopNum, 
                tiling_data.ubPartDataNum,    
                tiling_data.smallCoreTailDataNum, tiling_data.bigCoreTailDataNum,
                tiling_data.tailBlockNum);
    */
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void sinc_custom_do(uint32_t blockDim, void *stream, float *x, float *z)
{
    sinc_custom<<<blockDim, nullptr, stream>>>(x, z);
}
#endif
